package com.ben.restjpademo.service;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import com.ben.restjpademo.domain.Authentication;
import com.ben.restjpademo.domain.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import sun.misc.BASE64Decoder;

import com.ben.restjpademo.dao.AuthenticationRepository;
import com.ben.restjpademo.dao.UserRepository;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

@RestController
@RequestMapping("/")
public class LoginAndLogoutController {


    @Resource AuthenticationRepository authRepository;
    @Resource UserRepository userRepository;

    @RequestMapping(value = "login/byname", method = RequestMethod.POST)
    public Map<String,Object> login(@RequestBody final UserLogin login,final ServletRequest req) throws ServletException, IOException {
        final HttpServletRequest request = (HttpServletRequest) req;
        String username=null;

        //String hostip=request.getRemoteAddr();
        Map<String,Object> result=new HashMap<String,Object>();


        //ur.setHostip(hostip);
        String loginname=new String(new BASE64Decoder().decodeBuffer(login.name));
        String loginpasswd=new String(new BASE64Decoder().decodeBuffer(login.password));
        Authentication authentication=authRepository.valiedNameAndPawd(loginname,loginpasswd);
        if (authentication==null) {
            result.put("message", "mismatch");
            return result;
        }else if(authentication.getThrscondition().equals(2)){
            //2=> blacklist;
            result.put("message", "refused");
            return result;
        }else{
            username=authentication.getUserByUserid().getName();


            int userid=authentication.getUserByUserid().getId();

            Date date = new Date();
            DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EE");
            System.out.println(df2.format(date)+"userName:"+username);
            Calendar cal=Calendar.getInstance();
            cal.setTime(new Date());
            int hour=cal.get(Calendar.HOUR_OF_DAY);
            int minute=cal.get(Calendar.MINUTE);
            int second=cal.get(Calendar.SECOND);
            long millisecond = hour*60*60*1000 + minute*60*1000 + second*1000;
            cal.setTimeInMillis(cal.getTimeInMillis()-millisecond);
            cal.setTimeInMillis(cal.getTimeInMillis()+26*60*60*1000 + 59*60*1000 + 59*1000);
            Date expdate=cal.getTime();
            String token=Jwts.builder().setSubject(username).claim("userid", userid)
                    .claim("algo", "HS256").setIssuedAt(new Date())
                    .setExpiration(expdate).signWith(SignatureAlgorithm.HS256, "secret").compact();
            result.put("message", "success");
            result.put("token", token);
            return result;
        }
    }

    private static class UserLogin {
        public String name;
        public String password;
    }


    @ResponseBody
    @RequestMapping(value={"api/logout/id={id}"},method=RequestMethod.GET)
    public String logout(@PathVariable("id") int id){
        User user=userRepository.findOne(id);
        String name=user.getName();
        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss EE");
        System.out.println(df.format(date)+"user:"+name+"exit");

        return name+"Bye Bye";
    }
}
